package pit.com.ordermobilesystem;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pit.com.ordermobilesystem.BaseFragment.TypeLoadingMore;
import pit.com.ordermobilesystem.adapter.OrderItemAdapter;
import pit.com.ordermobilesystem.constant.OrderConstant;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.provider.BaseProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider.ItemTable;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import pit.com.ordermobilesystem.widget.OrderDialog;
import android.content.ClipData.Item;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;



public class InvoiceActivity extends BaseFragmentActivity implements OrderConstant{
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_invoice);

		String total=getIntent().getStringExtra("total");
		TextView tv_total_invoice=(TextView) findViewById(R.id.tv_total_invoice);
		tv_total_invoice.setText(total);
		TextView tv_payment=(TextView) findViewById(R.id.tv_payment);
		tv_payment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sendInvoice();
				
			}
		});
		getActionBar().setDisplayHomeAsUpEnabled(true);
	    }
	    
	    public boolean validateForm(){
		    EditText tv_name=(EditText) findViewById(R.id.ed_name);
		    EditText tv_phone=(EditText) findViewById(R.id.ed_phone);
		    EditText tv_address=(EditText) findViewById(R.id.ed_address);
		    if(tv_name.getText().toString().equals("")){
			    tv_name.setTextColor(Color.RED);
			    return false;
		    }else{
			    tv_name.setTextColor(Color.BLACK);
		    }
		    if(tv_phone.getText().toString().equals("")){
			    tv_phone.setTextColor(Color.RED);
			    return false;
		    }else{
			    tv_phone.setTextColor(Color.BLACK);
		    }
		    if(tv_address.getText().toString().equals("")){
			    tv_address.setTextColor(Color.RED);
			    return false;
		    }else{
			    tv_address.setTextColor(Color.BLACK);
		    }
		    return true;
	    }
	    
	    public void sendInvoice(){
		    if(validateForm()){
			    JSONObject data=new JSONObject();
			    EditText tv_name=(EditText) findViewById(R.id.ed_name);
			    EditText tv_phone=(EditText) findViewById(R.id.ed_phone);
			    EditText tv_address=(EditText) findViewById(R.id.ed_address);
			    EditText ed_discount=(EditText) findViewById(R.id.ed_salescode);
			    
			    Cursor cursor = null;
			    try {
				    JSONObject shop = new JSONObject(OrderSharePreference.getShop(getApplicationContext()));
				     cursor = getContentResolver().query(
							OrderMobileProvider.ITEM_CONTENT_URI, null, ItemTable.NUMBER_ORDER+">0  AND "+ItemTable.SALE_ID+"="+shop.getInt("id") , null,
							null);			    	
			    	JSONObject infoShop=new JSONObject( OrderSharePreference.getShop(this));
				    data.put("sale_id",infoShop.getInt("id"));
				    data.put("name_order",tv_name.getText().toString() );
				    data.put("name_customer",tv_name.getText().toString() );
				    data.put("mobile_customer",tv_phone.getText().toString() );
				    data.put("date_order",""+System.currentTimeMillis() );
				    data.put("discount_code",ed_discount.getText().toString());
					String total=getIntent().getStringExtra("total");
				    data.put("sum_price",total);
				    data.put("discount",0);
				    data.put("description","");
				    data.put("is_finish","0");
				    data.put("order_id",0);
				    JSONArray arrayItems=new JSONArray();
				    if (cursor != null) {
					    arrayItems=BaseProvider.getJSONArrayFromCursor(cursor);
					    data.put("array_items", arrayItems);
				    }					    
				    new SendInvoice(TypeLoadingMore.LOADING_FIRST).execute(data.toString());
			    } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }finally{
				    if(cursor!=null) cursor.close();
			    }
		    }

	    }
	    

		class SendInvoice extends AsyncTask<String, JSONObject, JSONObject> {

			TypeLoadingMore typeLoading;
			Exception exception;
			int response_code;
			
			
			public SendInvoice(TypeLoadingMore typeLoading) {
				super();
				this.typeLoading = typeLoading;
			}
			protected void onPreExecute() {
				if(typeLoading==TypeLoadingMore.LOADING_FIRST){
					showProgressDialog(new DialogInterface.OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface dialog) {
							SendInvoice.this.cancel(true);
							dialog.dismiss();
						}


					});
				}

			}

			protected JSONObject doInBackground(final String... args) {
				OrderSystemHttpService httpService=new OrderSystemHttpService(OrderSharePreference.getHost(getApplicationContext()),OrderSharePreference.getPort(getApplicationContext()));
				try {
					
					JSONObject result=httpService.requestToService(OrderSystemHttpService.URL_SUBMIT_ORDER, args[0]);
					return result;

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					exception=e;
				} catch (HttpApiException e) {
					// TODO Auto-generated catch block
					exception=e;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					exception=e;
				}
				return null;
			}

			protected void onPostExecute(JSONObject result) {

				hideProgressDialog();

				
				if(exception!=null){
					showAlert("",exception.getMessage());
				}else{
					try {
						if(result.getString("status").equals("ok")){	
							JSONObject data=result.getJSONObject("data");
							ContentValues values=new ContentValues();
							values.put(ItemTable.NUMBER_ORDER,0);
							getContentResolver().update(OrderMobileProvider.ITEM_CONTENT_URI, values, ItemTable.NUMBER_ORDER+">0", null);
							OrderDialog dialog=new OrderDialog(InvoiceActivity.this,new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									finish();
									
								}
							});
							dialog.setData(data.getDouble("sum_price"), data.getDouble("discount"));
							dialog.show();
						}else{
							exception=new Exception(result.getString("error"));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}

		}	

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		    switch (item.getItemId()) {
		    // Respond to the action bar's Up/Home button
		    case android.R.id.home:
		        //NavUtils.navigateUpFromSameTask(this);
			    finish();
		        return true;
		    }
		    return super.onOptionsItemSelected(item);
		}
}
